//
//  UIImage+YuExt.m
//  HuLaQuan
//
//  Created by hok on 2/2/16.
//  Copyright © 2016 yuwubao. All rights reserved.
//

#import "UIImage+YuExt.h"

#import "GTMBase64.h"



@implementation UIImage (YuExt)

#define kCompressScale 3

- (NSString *)compressAndConvertToBase64
{
    NSString *string = nil;
    
    if (self) {
        CGSize oriSize = self.size;
        NSLog(@"ori size%f %f",oriSize.width,oriSize.height);
        CGSize newSize = CGSizeMake(oriSize.width/kCompressScale, oriSize.height/kCompressScale);
        NSLog(@"new size%f %f",newSize.width,newSize.height);
        UIGraphicsBeginImageContext(newSize);
        [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        NSData *imageData = UIImageJPEGRepresentation(newImage, 0.1);
        
        if ((imageData == nil) || ([imageData length] <= 0)) return string;
        
        string = [GTMBase64 stringByEncodingData:imageData];
    }
    
    return string;
}

- (NSString *)saveImageWithName:(NSString *)name
{
    NSString *path = name;
    
    NSString *returnPath = nil;
    if ([self writeToFileAtPath:[NSString stringWithFormat:@"%@/%@",[NSString photoDir],path]]) {
        returnPath = [NSString stringWithFormat:@"%@/%@",[NSString photoDir],path];
    }
    
    return returnPath;
}

- (BOOL)writeToFileAtPath:(NSString*)aPath {
    if ((self == nil) || (aPath == nil) || ([aPath isEqualToString:@""])) return NO;
    @try
    {
        NSData *imageData = nil;
        NSString *ext = [aPath pathExtension];
        if ([ext isEqualToString:@"png"])
        {
            imageData = UIImagePNGRepresentation(self);
        }
        else
        {
            // the rest, we write to jpeg
            // 0. best, 1. lost. about compress.
            CGSize oriSize = self.size;
            NSLog(@"ori size%f %f",oriSize.width,oriSize.height);
            CGSize newSize = CGSizeMake(oriSize.width/3, oriSize.height/3);
            NSLog(@"new size%f %f",newSize.width,newSize.height);
            UIGraphicsBeginImageContext(newSize);
            [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
            UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            
            NSLog(@"new image size%f %f",newImage.size.width,newImage.size.height);
            imageData = UIImageJPEGRepresentation(newImage, 0.1);
        }
        if ((imageData == nil) || ([imageData length] <= 0)) return NO;
        [imageData writeToFile:aPath atomically:YES];
        return YES;
    }
    @catch (NSException *e)
    {
        NSLog(@"create thumbnail exception.");
    }
    return NO;
}

@end
